import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:enjoy_plus_three/utils/http.dart';
import 'package:enjoy_plus_three/utils/logger.dart';
import 'package:enjoy_plus_three/utils/toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 定义用户信息
  Map userInfo = {"avatar": null, "nickName": null};
  final _nickController = TextEditingController();
  @override
  void initState() {
    setState(() {
      userInfo = widget.userInfo;
      _nickController.text = userInfo['nickName'] ?? '';
    });
    super.initState();
  }

  // 从相册or相机选择图片
  _selectAvatar() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 120,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    ToastUtil.showInfo('拍照功能');
                    _pickerImageFromGalleryOrCamera('camera');
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    // 区分平台
                    if (kIsWeb) {
                      ToastUtil.showInfo('web平台');
                      // image_picker_web or file_picker 上传能力
                    } else if (Platform.isAndroid) {
                      _pickerImageFromGalleryOrCamera('gallery');
                    }
                  },
                )
              ]));
        });
  }

  // 上传图片
  _pickerImageFromGalleryOrCamera(String text) async {
    final ImagePicker picker = ImagePicker();
    // Pick an image.
    final pickedFile = await picker.pickImage(
        source: text == 'gallery' ? ImageSource.gallery : ImageSource.camera);
    if (pickedFile != null) {
      try {
        FormData formData = FormData.fromMap({
          // MultipartFile.fromFile 将本地路径转成二进制数据 (接口需要)
          "file": await MultipartFile.fromFile(pickedFile.path),
          "type": "avatar"
        });
        final res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传头像失败');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
      } catch (e) {
        ToastUtil.showError('上传失败');
      } finally {
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: GestureDetector(
                          onTap: () {
                            _selectAvatar();
                          },
                          child: userInfo['avatar'] != null
                              ? Image.network(userInfo['avatar'],
                                  width: 30, height: 30)
                              : Image.asset('images/avatar_1.jpg',
                                  width: 30, height: 30),
                        )),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  decoration: const InputDecoration(
                      hintText: '请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                  controller: _nickController,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
